package com.xfc.web.controller.school;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xfc.common.annotation.Log;
import com.xfc.common.core.controller.BaseController;
import com.xfc.common.core.domain.AjaxResult;
import com.xfc.common.core.page.TableDataInfo;
import com.xfc.common.enums.BusinessType;
import com.xfc.common.utils.StringUtils;
import com.xfc.common.utils.poi.ExcelUtil;
import com.xfc.message.NoticeMessage;
import com.xfc.school.domain.*;
import com.xfc.school.service.*;
import com.xfc.wx.domain.ScWxUser;
import com.xfc.wx.service.IScWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 学生购买课程Controller
 * 
 * @author lcj
 * @date 2021-12-09
 */
@Api(value = "course", tags = "购买课程管理接口")
@RestController
@RequestMapping("/school/course")
public class ScBuyCourseController extends BaseController
{
    @Autowired
    private IScBuyCourseService scBuyCourseService;
    @Autowired
    private IScCourseService courseService;

    @Autowired
    private IScStudentService studentService;

    @Autowired
    private IScMarketingCourseService scMarketingCourseService;

    @Autowired
    private IScClassEvaluationFormService scClassEvaluationFormService;

    @Autowired
    private IScCourseService scClassService;

    @Autowired
    private IScStudentService scStudentService;
    /**
     * 查询学生购买课程列表
     */
    @ApiOperation("查询学生购买课程列表")
    @PreAuthorize("@ss.hasPermi('school:course:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScBuyCourse scBuyCourse)
    {
        startPage();
        List<ScBuyCourse> list = scBuyCourseService.list(Wrappers.query(scBuyCourse)
                .orderByDesc("create_time"));
        list.forEach(l->{
            //查询课程信息
           ScCourse course =courseService.getById(l.getClassId());
           if (Objects.nonNull(course)){
               l.setClassId(course.getId());
               l.setCourseName(course.getClassName());
           }
           //学生姓名
           ScStudent student=studentService.getById(l.getStudentId());
           if (Objects.nonNull(student)){
               l.setStudentId(student.getId());
               l.setStudentName(student.getStudentName());
           }
        });
        return getDataTable(list);
    }


    /**
     * 查询课程人数
     * @param scBuyCourse
     * @return
     */
    @GetMapping("/list/schedule")
    public TableDataInfo listSchedule(ScBuyCourse scBuyCourse) {
        startPage();
        QueryWrapper<ScBuyCourse> queryWrapper1=new QueryWrapper<>();

        queryWrapper1.apply(
                "date_format (start_time,'%Y-%m-%d') <= date_format('" +scBuyCourse.getCourseStartime()+ "','%Y-%m-%d')");
        queryWrapper1.apply(
                "date_format (end_time,'%Y-%m-%d') >= date_format('" +scBuyCourse.getCounrseEndtime()+ "','%Y-%m-%d')");
        queryWrapper1.eq("class_id",scBuyCourse.getClassId());
        queryWrapper1.orderByAsc("create_time");

        List<ScBuyCourse> list = scBuyCourseService.list(queryWrapper1);

        list.forEach(l->{
            //学生姓名
            ScStudent student=studentService.getById(l.getStudentId());
            if (Objects.nonNull(student)){
                l.setStudentName(student.getStudentName());
                l.setStudentSex(String.valueOf(student.getStudentSex()));
                l.setStudentAge(String.valueOf(getAgeByBirth(student.getStudentBirthday())));
            }
            //查询是否销课
            QueryWrapper<ScMarketingCourse> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("student_id",l.getStudentId());
            queryWrapper.eq("course_id",l.getClassId());
//            queryWrapper.eq("course_startime",scBuyCourse.getCourseStartime());
//            queryWrapper.eq("counrse_endtime",scBuyCourse.getCounrseEndtime());
            queryWrapper.apply(
                    "date_format (course_startime,'%Y-%m-%d %h-%m') = date_format('" +scBuyCourse.getCourseStartime()+ "','%Y-%m-%d %h-%m')");
            ScMarketingCourse marketingCourse = scMarketingCourseService.getOne(queryWrapper);
            if (Objects.nonNull(marketingCourse)){
                l.setMarketingState(marketingCourse.getState());
            }
            //查询课堂评价的id
            QueryWrapper<ScClassEvaluationForm> queryWrapper3=new QueryWrapper<>();
//            queryWrapper3.eq("start_time",scBuyCourse.getCourseStartime());
//            queryWrapper3.eq("end_time",scBuyCourse.getCounrseEndtime());
            queryWrapper3.apply(
                    "date_format (start_time,'%Y-%m-%d %h-%m') = date_format('" +scBuyCourse.getCourseStartime()+ "','%Y-%m-%d %h-%m')");
            queryWrapper3.eq("course_number",scBuyCourse.getClassId());
            queryWrapper3.eq("student_number",l.getStudentId());
            List<ScClassEvaluationForm> listEvaluation = scClassEvaluationFormService.list(queryWrapper3);
            listEvaluation.forEach(l3->{
                l.setEvaluationId(l3.getId());
            });

        });

        return getDataTable(list);
    }

    /**
     * 获取年龄
     * @param birthday
     * @return
     */
    public static int getAgeByBirth(Date birthday){
        //Calendar：日历
        /*从Calendar对象中或得一个Date对象*/
        Calendar cal = Calendar.getInstance();
        /*把出生日期放入Calendar类型的bir对象中，进行Calendar和Date类型进行转换*/
        Calendar bir = Calendar.getInstance();
        bir.setTime(birthday);
        /*如果生日大于当前日期，则抛出异常：出生日期不能大于当前日期*/
        if(cal.before(birthday)){
            throw new IllegalArgumentException("The birthday is before Now,It's unbelievable");
        }
        /*取出当前年月日*/
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayNow = cal.get(Calendar.DAY_OF_MONTH);
        /*取出出生年月日*/
        int yearBirth = bir.get(Calendar.YEAR);
        int monthBirth = bir.get(Calendar.MONTH);
        int dayBirth = bir.get(Calendar.DAY_OF_MONTH);
        /*大概年龄是当前年减去出生年*/
        int age = yearNow - yearBirth;
        /*如果出当前月小与出生月，或者当前月等于出生月但是当前日小于出生日，那么年龄age就减一岁*/
        if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
            age--;
        }
        return age;
    }
    /**
     * 导出学生购买课程列表
     */
    @ApiOperation("导出学生购买课程列表")
    @PreAuthorize("@ss.hasPermi('school:course:export')")
    @Log(title = "学生购买课程", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ScBuyCourse scBuyCourse)
    {
        List<ScBuyCourse> list = scBuyCourseService.list(Wrappers.query(scBuyCourse));
        ExcelUtil<ScBuyCourse> util = new ExcelUtil<>(ScBuyCourse.class);
        return util.exportExcel(list, "course");
    }

    /**
     * 获取学生购买课程详细信息
     */
    @ApiOperation("获取学生购买课程详细信息")
    @PreAuthorize("@ss.hasPermi('school:course:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        ScBuyCourse buyCourse=scBuyCourseService.getById(id);
        if (Objects.nonNull(buyCourse)){
            //查询课程名称
            ScCourse course=scClassService.getById(buyCourse.getClassId());
            if (Objects.nonNull(course)){
                buyCourse.setClassId(course.getId());
                buyCourse.setCourseName(course.getClassName());
            }else{
                buyCourse.setClassId("暂无");
            }
            //查询课程名称
            ScStudent student=scStudentService.getById(buyCourse.getStudentId());
            if (Objects.nonNull(student)){
                buyCourse.setStudentName(student.getStudentName());
                buyCourse.setStudentId(student.getId());
            }else{
                buyCourse.setStudentId("暂无");
            }
        }

        return AjaxResult.success(buyCourse);
    }

    /**
     * 新增学生购买课程
     */
    @ApiOperation("新增学生购买课程")
    @PreAuthorize("@ss.hasPermi('school:course:add')")
    @Log(title = "学生购买课程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScBuyCourse scBuyCourse)
    {
        //添加剩余课时
        scBuyCourse.setClassSurplusTime(scBuyCourse.getClassTime());
        scBuyCourse.setCreateTime(new Date());
        return toAjax(scBuyCourseService.save(scBuyCourse));
    }

    /**
     * 修改学生购买课程
     */
    @ApiOperation("修改学生购买课程")
    @PreAuthorize("@ss.hasPermi('school:course:edit')")
    @Log(title = "学生购买课程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScBuyCourse scBuyCourse)
    {
        scBuyCourse.setUpdateTime(new Date());
        return toAjax(scBuyCourseService.updateById(scBuyCourse));
    }

    /**
     * 删除学生购买课程
     */
    @ApiOperation("删除学生购买课程")
    @PreAuthorize("@ss.hasPermi('school:course:remove')")
    @Log(title = "学生购买课程", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids){
		List<String> list=new ArrayList<>();
    	if (ids!=null&&ids.length>0) {
            for (String id : ids) {
                list.add(id);
            }
		}
        return toAjax(scBuyCourseService.removeByIds(list));
    }

    /**
     * 根据学生id查询购买的课程
     */
    @ApiOperation("根据学生id查询购买的课程")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="学生id",dataTypeClass = String.class),
    })
    @GetMapping("/getCourseByUserId/{id}")
    public AjaxResult getCourseByUserId(@PathVariable String id){
        if (StringUtils.isEmpty(id)){
            return AjaxResult.error("没有查询到用户信息");
        }
        //查询课程信息
        QueryWrapper<ScBuyCourse> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("student_id",id);
//        queryWrapper.le("end_time",new Date());
        List<ScBuyCourse> list=scBuyCourseService.list(queryWrapper);
        list.forEach(l->{
            //查询课程名称
            if (Objects.nonNull(l.getClassId())){
                ScCourse scClass=courseService.getById(l.getClassId());
                if (Objects.nonNull(scClass)){
                    //课程名称
                    l.setClassId(scClass.getClassName());
                }
            }
        });
        return AjaxResult.success(list);
    }
}
